import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';
import 'package:xindong/manager/xindong_tencent_singleton.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/conversation/emoji/xindong_emoji_item.dart';
import 'package:xindong/routes/conversation/emoji/xindong_emoji_class.dart';
import 'package:xindong/routes/conversation/input/xindong_liaotianInputButtonModel.dart';
import 'package:xindong/routes/conversation/input/xindong_liaotian_input_controller.dart';
import 'package:xindong/routes/conversation/input/xindong_liaotian_keyboard_controller.dart';
import 'package:xindong/routes/conversation/input/xindong_liaotian_input_text_voice_view.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/widgets/gift/xindong_songli_sheet.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

// 会话输入组件 文字、语音、图片
class XinDongLiaoTianInputWidget extends StatefulWidget {
  final V2TimConversation conversation;
  final String userId;

  const XinDongLiaoTianInputWidget({Key? key, required this.conversation, required this.userId}) : super(key: key);

  @override
  State<XinDongLiaoTianInputWidget> createState() => _XinDongLiaoTianInputWidgetState();
}

class _XinDongLiaoTianInputWidgetState extends State<XinDongLiaoTianInputWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: DZColors.cellColor,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 10),
              // 文字、语音
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  const SizedBox(width: 16),
                  GetBuilder<XinDongLiaoTianKeyBoardController>(builder: (provider) {
                    return Container(
                      width: 48,
                      height: 48,
                      alignment: Alignment.center,
                      // decoration: BoxDecoration(borderRadius: BorderRadius.circular(16), color: DZColors.white),
                      child: IconButton(
                        padding: EdgeInsets.zero,
                        icon: ImageUtil.asset(provider.show ? AssetsRes.CHAT_VOICE : AssetsRes.CHAT_CHAT_KEYBOARD),
                        onPressed: () async {
                          XinDongLiaoTianInputController.to.closeAll();
                          bool havePermission =
                              await XinDongPermissionCtr.checkPermission(XinDongAppPermission.microphone);
                          if (havePermission == false) {
                            showToast("语音聊天需要开启麦克风权限");
                            return;
                          }
                          provider.setStatus(!provider.show);
                        },
                      ),
                    );
                  }),
                  const SizedBox(width: 10),
                  XinDongLiaoTianInputTextVoice(userId: widget.userId, conversation: widget.conversation),
                  const SizedBox(width: 16),
                ],
              ),

              /// 表情、礼物、图片、拍照
              SizedBox(
                height: 70,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: inputButtons.map((e) => e.child).toList(),
                ),
              ),
            ],
          ),

          /// 表情包
          GetBuilder<XinDongLiaoTianInputController>(builder: (controller) {
            return Offstage(
              offstage: !controller.upSpring,
              child: showEmojiView(context),
            );
          }),

          // 安全区域，使用MediaQuery.of(context).padding.bottom，键盘抬起时自动改变高度
          SizedBox(height: MediaQuery.of(context).padding.bottom),
        ],
      ),
    );
  }

  List<XinDongLiaoTianInputButtonClass> get inputButtons {
    var inputList = [
      XinDongLiaoTianInputButtonClass(
        type: XinDongLiaoTianInputButtonType.camera,
        child: createButton(
          name: "拍照",
          iconName: AssetsRes.CHAT_CAMERA,
          onTap: () {
            XinDongLiaoTianInputController.to.closeAll();
            sendImageMessage(context, 0);
          },
        ),
      ),
      XinDongLiaoTianInputButtonClass(
        type: XinDongLiaoTianInputButtonType.album,
        child: createButton(
          name: "相册",
          iconName: AssetsRes.CHAT_ALBUM,
          onTap: () {
            XinDongLiaoTianInputController.to.closeAll();
            sendImageMessage(context, 1);
          },
        ),
      ),
      // XinDongLiaoTianInputButtonClass(
      //   type: XinDongLiaoTianInputButtonType.quick,
      //   child: createButton(
      //     name: "快捷消息",
      //     iconName: 'icon_quickReply',
      //     onTap: () {
      //       Provider.of<XinDongLiaoTianInputProvider>(context, listen: false).close();
      //       Provider.of<XinDongLiaoTianInputProvider>(context, listen: false).closeMiniGames();
      //       FocusScope.of(context).requestFocus(FocusNode());
      //       XinDongQuickReplyDialog.show(widget.userClass, context);
      //     },
      //   ),
      // ),
      XinDongLiaoTianInputButtonClass(
        type: XinDongLiaoTianInputButtonType.call,
        child: createButton(
          name: "通话",
          iconName: AssetsRes.CHAT_CALL,
          onTap: () {
            XinDongLiaoTianInputController.to.closeAll();
            XinDongPageSingleton.instance.calling(model: XinDongChatSingleton.instance.detailClass);
          },
        ),
      ),
      XinDongLiaoTianInputButtonClass(
        type: XinDongLiaoTianInputButtonType.gift,
        child: createButton(
          name: "送礼物",
          iconName: AssetsRes.CHAT_GIFT,
          onTap: () {
            XinDongLiaoTianInputController.to.closeAll();
            if (widget.conversation.type != ConversationType.V2TIM_C2C) {
              showToast("Un support");
              return;
            }
            if (widget.userId == XinDongTencentSingleton.instance.customerID) {
              showToast("不支持客服送礼");
              return;
            }
            final user = XinDongChatSingleton.instance.detailClass?.another;
            if (user == null) return;
            XinDongSongLiSheet.show(
                user: user,
                onSuccess: (model, count) {
                  Navigator.pop(context);
                  // showToast("发送成功", milliseconds: 2000);
                });
          },
        ),
      ),
      // XinDongLiaoTianInputButtonClass(
      //   type: XinDongLiaoTianInputButtonType.camera,
      //   child: Consumer<XinDongLiaoTianInputController>(builder: (context, provider, child) {
      //     return Stack(
      //       clipBehavior: Clip.none,
      //       children: [
      //         createButton(
      //           iconName: provider.miniGames ? 'icon_chat_close' : 'icon_more',
      //           onTap: () {
      //             FocusScope.of(context).requestFocus(FocusNode());
      //             provider.close();
      //             provider.newFunction = true;
      //             provider.onMiniGames();
      //           },
      //           name: '小游戏',
      //         ),
      //         // provider.newFunction
      //         //     ? SizedBox()
      //         //     : Positioned(
      //         //         top: -20,
      //         //         right: -8,
      //         //         child: Container(
      //         //           width: 81,
      //         //           height: 24,
      //         //           padding: EdgeInsets.only(bottom: 5),
      //         //           decoration: BoxDecoration(image: DecorationImage(image: AssetImage("assets/images/image_Connecting.png"))),
      //         //           child: Row(
      //         //             mainAxisAlignment: MainAxisAlignment.center,
      //         //             children: [
      //         //               Text(
      //         //                 "新功能上线啦~",
      //         //                 style: TextStyle(color: DZColors.white, fontSize: 9, fontWeight: FontWeight.normal),
      //         //               ),
      //         //             ],
      //         //           ),
      //         //         ),
      //         //       ),
      //       ],
      //     );
      //   }),
      // ),
    ];
    // // 是否移除呼叫按钮
    // if (XinDongAccountUser.showCall(widget.userClass) == false) {
    //   inputList.removeWhere((element) => element.type == XinDongLiaoTianInputButtonType.call);
    // }
    // // 是否移除快捷用语按钮
    // if (XinDongAccountUser.mineUserClass.isAnchor == false) {
    //   inputList.removeWhere((element) => element.type == XinDongLiaoTianInputButtonType.quick);
    // }
    return inputList;
  }

  Widget showEmojiView(BuildContext context, {Function(String charCode)? onTap}) {
    final double itemSize = (screenWidth - 16) / 8;
    List<Widget> dataList = [];
    void close() {
      Navigator.pop(context);
    }

    dataList = emojiData.map(
      (e) {
        var item = XinDongEmojiClass.fromJson(e);
        return Container(
          width: itemSize,
          height: itemSize,
          alignment: Alignment.center,
          child: XinDongEmojiItem(name: item.name, unicode: item.unicode, close: close),
        );
      },
    ).toList();
    return GestureDetector(
      onTap: () {},
      child: Container(
        height: 246 + bottomBarHeight,
        color: DZColors.backgroundColor,
        child: GridView.count(
          padding: const EdgeInsets.fromLTRB(8, 0, 8, 16),
          crossAxisCount: 8,
          children: dataList,
        ),
      ),
    );
  }

  // 创建按钮
  Widget createButton({required String name, required String iconName, bool isPng = true, required Function() onTap}) {
    return Theme(
      data: ThemeData(
        highlightColor: DZColors.mainLightColor,
        splashColor: DZColors.mainLightColor,
      ),
      child: IconButton(
        icon: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ImageUtil.asset(iconName, width: 24, height: 24),
            // isPng ? ImageHelper.asset(iconName) : ImageHelper.assetWebp(iconName, fit: BoxFit.contain),
            const SizedBox(height: 5),
            Text(
              name,
              style: const TextStyle(fontSize: 10, fontWeight: FontWeight.normal, color: DZColors.placeholderColor),
            ),
          ],
        ),
        padding: EdgeInsets.zero,
        onPressed: onTap,
      ),
    );
  }

  /// 发送图片
  ///
  /// checkType 0拍照 1相册
  void sendImageMessage(context, checkType) async {
    File? file;
    if (checkType == 0) {
      file = await ImageUtil.takePhoto();
    } else {
      List<File>? list = await ImageUtil.selectPhotos(maxCount: 1);
      file = list!.first;
    }
    if (file == null) {
      return;
    }
    String path = file.path;
    XinDongChatSingleton.instance.requestSendImage(filePath: path);
  }
}
